﻿using MiniExcelLibs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LuckLottery
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        bool IsRun = false;
        List<string> NameList;

        /// <summary>
        /// 已中奖名单
        /// </summary>
        List<LuckPerson> LuckList;
        int n = -1;

        int count = 1;

        public MainWindow()
        {
            InitializeComponent();

            NameList = new List<string>();
            LuckList = new List<LuckPerson>();
            SettingGrid.Visibility = Visibility.Hidden;
            Init();
        }

        void Init()
        {
            if (File.Exists("Title.txt"))
            {
                TitleTxt.Text = File.ReadAllText("Title.txt");
            }
            if (File.Exists("中奖名单.txt"))
            {
                try
                {
                    //LuckList = MiniExcel.Query<LuckPerson>("中奖名单.xlsx").ToList();
                    var lines = File.ReadAllLines("中奖名单.txt");
                    foreach (var line in lines)
                    {
                        var values = line.Split(',');
                        LuckList.Add(
                            new LuckPerson { Name = values[0], Time = DateTime.Parse(values[1]) }
                        );
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("中奖名单 打开失败");
                }
            }
            if (File.Exists("名单.xlsx"))
            {
                var list = MiniExcel.Query("名单.xlsx").ToList();
                foreach (var item in list)
                {
                    if (item.A != null && item.A.ToString() != "")
                    {
                        NameList.Add(item.A.ToString());
                    }
                }
            }
            else
            {
                MessageBox.Show("没有人员名单!");
            }

            foreach (var item in LuckList)
            {
                NameList.Remove(item.Name);
            }
        }

        private void Running(object sender)
        {
            while (IsRun)
            {
                n++;
                if (n > NameList.Count - count)
                {
                    n = 0;
                }
                this.Dispatcher.Invoke(() =>
                {
                    NamesListBox.Items.Clear();
                    for (int i = 0; i < count; i++)
                    {
                        NamesListBox.Items.Add(NameList[n + i]);
                    }
                });
                Thread.Sleep(10);
            }
            //中奖
            this.Dispatcher.Invoke(() =>
            {
                foreach (string item in NamesListBox.Items)
                {
                    LuckList.Add(new LuckPerson(item));
                    NameList.Remove(item);
                }

                try
                {
                    MiniExcel.SaveAs("中奖名单.xlsx", LuckList, overwriteFile: true);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("文件被打开，中奖名单未录入");
                }
            });
        }

        // Fisher-Yates 洗牌算法
        public static void Shuffle(List<string> array)
        {
            Random random = new Random();
            int n = array.Count;
            for (int i = 0; i < n - 1; i++)
            {
                int j = random.Next(i, n);
                // 交换 array[i] 和 array[j]
                string temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var btn = (Button)sender;
            if (!IsRun)
            {
                if (NameList.Count <= count)
                {
                    MessageBox.Show("待抽奖人数过少，请重置抽奖目录，直接显示剩余全程未中奖的幸运儿");
                    NamesListBox.Items.Clear();
                    foreach (string item in NameList)
                    {
                        NamesListBox.Items.Add(item);
                    }
                    return;
                }
                Shuffle(NameList);
                n = -1;
                btn.Content = "停止";
                IsRun = true;
                ThreadPool.QueueUserWorkItem(Running);
            }
            else
            {
                IsRun = false;
                btn.Content = "开始抽奖";
            }
        }

        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            count = 1;
        }

        private void RadioButton_Checked_1(object sender, RoutedEventArgs e)
        {
            count = 2;
        }

        private void RadioButton_Checked_2(object sender, RoutedEventArgs e)
        {
            count = 3;
        }

        private void RadioButton_Checked_3(object sender, RoutedEventArgs e)
        {
            count = 5;
        }

        private void RadioButton_Checked_4(object sender, RoutedEventArgs e)
        {
            count = 10;
        }

        bool isShow = false;

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (isShow)
            {
                SettingGrid.Visibility = Visibility.Hidden;
                isShow = false;
            }
            else
            {
                SettingGrid.Visibility = Visibility.Visible;
                isShow = true;
            }
        }
    }

    public class LuckPerson
    {
        public string Name { get; set; }
        public DateTime Time { get; set; }

        public LuckPerson() { }

        public LuckPerson(string name)
        {
            Name = name;
            Time = DateTime.Now;
        }
    }
}
